﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Util
{
    public class UrlUtil
    {
        public static bool IsFullUrl(string link)
        {
            if (string.IsNullOrEmpty(link))
            {
                return false;
            }
            link = link.Trim().ToLowerInvariant();
            return link.StartsWith("http://") || link.StartsWith("https://");
        }

        public static string FullUrl(string url, string link)
        {
            link = link.Replace("&amp;", "");//去掉垃圾字符
            if (IsFullUrl(link))
            {
                return link;
            }

            //去掉锚点
            if (url.Contains('#'))
            {
                int end = url.IndexOf('#');
                string tem = url.Substring(0, end);
                url = tem;
            }

            //直接get传参的
            if (link.StartsWith("?"))
            {
                string absolute = string.Empty;

                if (!url.Contains('?'))
                {
                    absolute = url + link;
                }
                else
                {
                    int end = url.IndexOf('?');
                    string tem = url.Substring(0, end);
                    absolute = tem + link;
                }
                return absolute;
            }

            Uri pu = new Uri(url);
            Uri uri = new Uri(pu, link);
            return uri.AbsoluteUri;
        }

        public static string GetTopDomain(string url)
        {
            string host = GetHost(url);
            Regex regex = new Regex(@"\.(.*\..*)");
            Match m = regex.Match(host);
            string top = m.Groups[1].Value;
            return top;
        }

        public static string GetHost(string url)
        {
            Uri uri = new Uri(url);
            return uri.Host;
        }

        public static string FormatUrlToFileName(string url)
        {
            return url.Replace(@"\", "").Replace("/", "").Replace(":", "").Replace("*", "").Replace("?", "").Replace("\"", "")
               .Replace("<", "").Replace(">", "").Replace("|", "").Replace(".", "").Replace("=", "").Replace("&", "");
        }
    }
}
